import React, { useEffect, useState } from 'react';
import styles from './index.less';
import {
  Form,
  DatePicker,
  Select,
  Button,
  message,
  Tooltip,
  Space,
  Progress,
  Dropdown,
} from 'antd';
import { useDebounceFn } from 'ahooks';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';
import { getAllMarketingUnit } from '@/tjComponents/TjMarketingUnit/utils';

import { TjStation } from '@/pages/ETrade/components/index.js';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import { convertResult, getDefaultParams } from '@/hooks/useRequestPowerAfterInit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import { QuestionCircleOutlined, PlusCircleOutlined } from '#/utils/antdIcons.js';
import {
  CaretLeftOutlined,
  CaretRightOutlined,
  FileTextOutlined,
  CaretDownOutlined,
  FileSearchOutlined,
  FullscreenOutlined,
  CalendarOutlined,
  UpSquareOutlined,
  DownSquareOutlined,
} from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components/index.js';
import { MENU_OPTIONS } from '@/components/TRTablePage/helper.js';
// import { useRem } from '@/hooks/index.js';
import useRem from '../../../tool/hooks/useRem.js';
import { getTreeByCodes } from '@/utils/index.js';

import {
  detailList,
  planOption,
  tabList,
  colorOptions,
  tableHead_2,
  OPTION_KEY,
  YearOptions,
  planParams,
  monthList,
} from './helper.js';
import {
  querypowerGenerationData,
  queryMarketList,
  powerGenerationStatusPlanCount,
  // powerGenerationStatusHljPlanCount,
  publishPowerGenerationPlan,
  useNewServers,
} from './services.js';
import { PlanYearTable, PlanMonthTable } from './components/BaseTable';
import MyDrawer from './components/MyDrawer/index.jsx';
import PowerGenerationPlanSurvey from './components/PowerGenerationPlanSurvey';
import GenerationPlan from './components/GenerationPlan';
import MonthRatio from './components/MonthRatio';
import CheckedList from './components/CheckedList';
import ExportModal from './components/ExportModal';
import HistoryShot from './components/HistoryShot';
import RadioBoxModal from './components/RadioBoxModal/index.jsx';
import {
  ChartDealYearBar,
  ChartDealYearLine,
  ChartDealMonthLine,
} from './components/Charts/index.js';

let isFirst = true;
const initialValues = {
  date: moment(),
  plan: '0',
};
const MySelect = (props: any) => {
  const { value = [], onChange, options = [] } = props;
  return (
    <>
      <Select
        showSearch={false}
        value={value}
        options={options}
        style={{ width: 120 }}
        placeholder="请选择参考年份"
        mode="multiple"
        maxTagCount={1}
        maxTagTextLength={4}
        onChange={onChange}
        dropdownRender={() =>
          options.length ? (
            <CheckedList options={options} onChange={onChange} value={value} />
          ) : (
            <TRDefault type="emptysm" />
          )
        }
      />
      <CalendarOutlined className={styles.icon_calendar} />
    </>
  );
};
const PowerGenerationPlan = ({ menuCode, buttonPermissions }: any) => {
  const [loading, setLoading] = useState(true),
    [firstLoding, setFirstLoding] = useState(false),
    [plannedQuantity, setPlannedQuantity] = useState(tabList),
    [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false), // 是否为图表全屏展示
    [isFullScreenTable, setIsFullScreenTable] = useState(false), // 是否为表格全屏展示
    [stations, setStations] = useState<any>([]), // 全部场站（平铺）
    [stationTree, setStationTree] = useState<any>([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState<any>([]), //所选省份全部场站(全选)
    [tableYearHead, setTableYearHead] = useState<any>({}), //年计划表头
    [ehartDealYearBarData, setEhartDealYearBarData] = useState<any>({}), //计划参考柱状
    [echartsPlanYearLine, setEchartsPlanYearLineData] = useState<any>({}), //计划参考折线（全部）
    [echartsPlanMonthLineData, setEchartsPlanMonthLineData] = useState<any>({}), //计划参考（月计划）
    [referenceYearOptions, setReferenceYearOptions] = useState<any[]>([]), //参考年份列表
    [tableYearData, setTableYearData] = useState<any>([]),
    [tableMonthData, setTableMonthData] = useState<any>([]),
    [yearAllEchartsData, setYearAllEchartsData] = useState<any>([]),
    [monthAllEchartsData, setMonthAllEchartsData] = useState<any>([]),
    [radioData, setRadioData] = useState<any>([]),
    [totalRatio, setTotalRatio] = useState<any>(), //总完成比率
    [expand, setExpand] = useState(false),
    [form] = Form.useForm(),
    [echarstitle, setTitle] = useState('全部交易单元'),
    [formData, setFormData] = useState<any>({}),
    reSize = useRem(1920);

  const [province, setProvince] = useState<any[]>([]);
  const [defaultItem, setDefaultItem] = useState<any>({});
  const [treeData, setTreeData] = useState<any[]>([]);
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<any>();
  const [curMarketId, setCurMarketId] = useState(''); //缓存当前选中的marketId
  const [searchMarketId, setSearchMarketId] = useState(''); //点击搜索之后的marketId

  const [curDefaultUnit, setCurDefaultUnit] = useState([] as any); //初始化加载默认的单元
  useEffect(() => {
    init();
  }, []);

  // useEffect(() => {
  //   if(province && province.length>0) {
  //     changeMarketId(province[0]?.value);
  //   }
  // }, [province]);

  /** handle data */
  async function init() {
    // 获取数据权限
    setFirstLoding(true);
    const res = await queryMarketList(menuCode).catch(() => setLoading(false));
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { treeOptions, allKeys } = getTreeByCodes(['market', 'group', 'station'], res.json);

      const _stations = _.flattenDeep(
        treeOptions.map((t: any) => t?.children.map((k: any) => k?.children)),
      );

      setOptionAll(allKeys); //所有的交易单元的所有的key——>stationId
      setStations(_stations); //全部交易单元扁平化之后的数组json
      setStationTree(treeOptions);

      // _onReset.run();

      //下面是新添加的逻辑
      const data: any[] = _.get(res, 'data', _.get(res, 'json', []));
      if (data.length > 0) {
        const { provinceArr, treeData } = convertResult(data, '2');
        // const defaultParams = getDefaultParams(0, provinceArr);
        // setDefaultItem(defaultParams);

        if (provinceArr && provinceArr.length > 0) {
          setDefaultItem(provinceArr[0]);
        }
        setTreeData(treeData);
        setProvince(provinceArr);

        _onReset.run();

        changeMarketId(provinceArr[0]?.value);
        setCurMarketId(provinceArr[0]?.value);

        const defaultUnit = getDefaultUnit(provinceArr[0].value, treeData);
        // getBordData(moment(), defaultUnit);
      }
    }
    setFirstLoding(false);
  }

  //交易中心改变事件
  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      setCurMarketId(item.value);
      form.setFieldsValue({
        stationIdList: item.stations.map((v: StationType) => {
          return v.stationId;
        }),
      });
    }
  };

  //一进入页面，得到默认的所有的交易单元
  const getDefaultUnit = (marketId: any, treeData: any) => {
    let data = treeData;
    if (marketId) {
      const item = _.find(data, (n: any) => n.key === marketId);
      data = item.children ? item.children : [];
    }
    const marketingUnit = getAllMarketingUnit(data);
    setCurDefaultUnit(marketingUnit.map((v) => v.key));
    return marketingUnit.map((v) => v.key);
  };

  async function getBordData(year = moment(), unit: any) {
    let data: any = {
      year: moment(year).format('YYYY'),
      stationIdList: unit,
    };
    if (useNewServers.includes(curMarketId)) {
      data = {
        ...data,
        marketId: curMarketId,
      };
    }
    const res = await powerGenerationStatusPlanCount(
      // { year: moment(year).format('YYYY'), stationIdList: form.getFieldValue('stationIdList') },
      // { year: moment(year).format('YYYY'), stationIdList: unit },
      data,
      curMarketId,
    ).catch();
    if (res?.statusCode === HttpCode.SUCCESS) {
      const statusToCount = res.data.statusToCount;
      const value_1 = (statusToCount[0] || 0) + (statusToCount[-1] || 0) + (statusToCount[1] || 0);
      const arr = [
        {
          name: tabList[0],
          value: value_1,
        },
        {
          name: tabList[1],
          value: statusToCount[1] || 0,
          radio: Math.round(((statusToCount[1] || 0) / value_1) * 100),
        },
        {
          name: tabList[2],
          value: statusToCount[-1] || 0,
          radio: Math.round(((statusToCount[-1] || 0) / value_1) * 100),
        },
        {
          name: tabList[3],
          value: statusToCount[0] || 0,
          radio: Math.round(((statusToCount[0] || 0) / value_1) * 100),
        },
        {
          name: tabList[4],
          value: statusToCount[2] || 0,
          radio: Math.round(((statusToCount[2] || 0) / value_1) * 100),
        },
      ];
      setPlannedQuantity(arr);
    }
  }

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenTable) {
      classNameEcharts = `${styles.chartsFullWidth}`;
      classNameTable = `${styles.tableNoWidth}`;
    } else if (isFullScreenEcharts) {
      classNameEcharts = `${styles.chartsNoWidth}`;
      classNameTable = `${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };
  //月份数据加总
  const monthToYear = (val: any) => {
    if (!val?.length) return '0';
    else
      return val.some((t: any) => t !== null)
        ? parseFloat(val.reduce((a: number, b: number) => a + b)).toFixed(3)
        : null;
  };
  const descSort = (val: any) => {
    return val.sort((a: any, b: any) => {
      return b.title.substring(0, 4) === a.title.substring(0, 4)
        ? a.title.includes('计划')
          ? -1
          : 0
        : b.title.substring(0, 4) - a.title.substring(0, 4);
    });
  };
  //处理完成比例数据
  const getNewRadioData = (data: any) => {
    let _data: any = [];
    const count: any = { title: '合计' };
    //年计划
    _data = Object.entries(data).map((t: any) => {
      const _temp: any = {
        title: stations.find((_t: any) => _t.stationId === t[0]).label,
      };
      Object.entries(t[1].numerical).forEach((_t: any) => {
        Object.entries(_t[1]).forEach((_t_: any) => {
          _temp[`${_t_[0]}`] = monthToYear(_t_[1]);
          //合计
          count[`${_t_[0]}`] = (count[`${_t_[0]}`] || 0) + _t_[1].reduce((a: any, b: any) => a + b);
        });
      });
      if (!_temp.operate || _temp.operate == 0) {
        _temp.radio = '-';
      } else {
        _temp.radio = Math.round(
          (_temp.settlement / ((_temp.operate || 0) == 0 ? 1 : _temp.operate)) * 100,
        );
      }
      return _temp;
    });
    //合计
    Object.keys(count).forEach((t: any) => {
      if (t === 'title') return;
      count[t] = parseFloat(count[t]).toFixed(3);
    });
    return { data: _data, count };
  };
  async function getRadioData(year = moment().format('YYYY')) {
    //请求表格数据
    const param: any = {
      reqDataScopes: [
        {
          // dataTypeList: ['settlement', 'operate'],
          dataTypeList: useNewServers.includes(curMarketId)
            ? ['huineng', 'guoneng', 'plan', 'settlement', 'operate']
            : ['settlement', 'operate'],
          year,
        },
      ],
      respDataTypes: ['numerical', 'proportion'],
      // stationIds: optionAll,
      stationIds: form.getFieldValue('stationIdList'),
    };

    if (useNewServers.includes(curMarketId)) {
      param.marketId = curMarketId;
    }

    //发起请求
    const res = await querypowerGenerationData(param, curMarketId).catch(() => setLoading(false));
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { data, count } = getNewRadioData(res.data || {});
      if (curMarketId === 'PDBLJ') {
        //黑龙江
        setTotalRatio(Math.round((count.settlement / (count.plan == 0 ? 1 : count.plan)) * 100));
      } else {
        setTotalRatio(
          Math.round((count.settlement / (count.operate == 0 ? 1 : count.operate)) * 100),
        );
      }

      setRadioData(data);
    }
  }
  // useEffect(()=>{
  //   console.log(radioData,'radioData')
  //   console.log(totalRatio,'totalRatio')
  // },[radioData, totalRatio])
  //处理表格数据
  const getNewTableData = (data: any, planType: any, _marketId: any, type: string) => {
    let _data: any = [];
    const count: any = { title: '合计', status: [] };

    if (planType == '0') {
      //年计划
      _data = Object.entries(data).map((t: any) => {
        const _temp: any = {
          title: stations.find((_t: any) => _t.stationId === t[0]).label,
          unitId: t[0],
          status: t[1].status,
        };
        Object.entries(t[1].numerical).forEach((_t: any) => {
          Object.entries(_t[1]).forEach((_t_: any) => {
            _temp[`${_t[0]}_${_t_[0]}`] = monthToYear(_t_[1]);
            //合计
            count[`${_t[0]}_${_t_[0]}`] =
              (count[`${_t[0]}_${_t_[0]}`] || 0) + _t_[1].reduce((a: any, b: any) => a + b);
          });
        });
        return _temp;
      });
      //合计
      Object.keys(count).forEach((t: any) => {
        if (t === 'title' || t === 'status') return;
        count[t] = count[t] == 0 ? null : parseFloat(count[t]).toFixed(3);
      });
      _data.unshift(count);
    } else {
      //月计划
      //判断是否是宁夏
      if (_marketId === 'PXBNX' && type !== 'PowerGenerationPlan') {
        _data = Object.entries(data).map((t: any) => {
          const _temp: any = {
            unit: stations.find((_t: any) => _t.stationId === t[0]).label,
            unitId: t[0],
            status: t[1].status,
            expand: false,
            data: [],
          };
          let year: string;
          Object.entries(t[1].numerical).forEach((_t: any) => {
            year = _t[0];
          });
          _temp.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((item) => {
            return {
              title: `${year}年${item}月`,
              // count: monthToYear(x[1][item - 1]),
              '00:00': parseFloat('0').toFixed(3),
              '01:00': parseFloat('0').toFixed(3),
              '02:00': parseFloat('0').toFixed(3),
              '03:00': parseFloat('0').toFixed(3),
              '04:00': parseFloat('0').toFixed(3),
              '05:00': parseFloat('0').toFixed(3),
              '06:00': parseFloat('0').toFixed(3),
              '07:00': parseFloat('0').toFixed(3),
              '08:00': parseFloat('0').toFixed(3),
              '09:00': parseFloat('0').toFixed(3),
              '10:00': parseFloat('0').toFixed(3),
              '11:00': parseFloat('0').toFixed(3),
              '12:00': parseFloat('0').toFixed(3),
              '13:00': parseFloat('0').toFixed(3),
              '14:00': parseFloat('0').toFixed(3),
              '15:00': parseFloat('0').toFixed(3),
              '16:00': parseFloat('0').toFixed(3),
              '17:00': parseFloat('0').toFixed(3),
              '18:00': parseFloat('0').toFixed(3),
              '19:00': parseFloat('0').toFixed(3),
              '20:00': parseFloat('0').toFixed(3),
              '21:00': parseFloat('0').toFixed(3),
              '22:00': parseFloat('0').toFixed(3),
              '23:00': parseFloat('0').toFixed(3),
            };
          });
          _temp.data = descSort(_temp.data);
          // Object.entries(t[1].numerical).forEach((_t: any) => {
          //   Object.entries(_t[1]).forEach((x: any) => {
          //     let total: any = '',
          //       title = '';
          //     const month: any = {};
          //     if (x[0].includes('plan')) {
          //       title = _t[0] + '年计划电量';
          //     }
          //     if (x[0].includes('operate')) {
          //       title = _t[0] + '年经营电量';
          //     }
          //     if (x[0].includes('guoneng')) {
          //       title = _t[0] + '年国能日新预测电量';
          //     }
          //     if (x[0].includes('huineng')) {
          //       title = _t[0] + '年金风慧能预测电量';
          //     }
          //     if (x[0].includes('settlement')) {
          //       title = _t[0] + '年结算电量';
          //     }
          //     total = monthToYear(x[1]);
          //     x[1]?.forEach((y: any, i: number) => {
          //       month[OPTION_KEY[i + 1]] = y !== null ? parseFloat(y).toFixed(3) : y;
          //     });
          //     if (total !== null) {
          //       _temp.data.push({
          //         title,
          //         count: total,
          //         ...month,
          //       });
          //     }
          //   });
          // });

          return _temp;
        });
      } else {
        _data = Object.entries(data).map((t: any) => {
          const _temp: any = {
            unit: stations.find((_t: any) => _t.stationId === t[0]).label,
            unitId: t[0],
            status: t[1].status,
            expand: false,
            data: [],
          };
          Object.entries(t[1].numerical).forEach((_t: any) => {
            Object.entries(_t[1]).forEach((x: any) => {
              let total: any = '',
                title = '';
              const month: any = {};
              if (x[0].includes('plan')) {
                title = _t[0] + '年计划电量';
              }
              if (x[0].includes('operate')) {
                title = _t[0] + '年经营电量';
              }
              if (x[0].includes('guoneng')) {
                title = _t[0] + '年国能日新预测电量';
              }
              if (x[0].includes('huineng')) {
                title = _t[0] + '年金风慧能预测电量';
              }
              if (x[0].includes('settlement')) {
                title = _t[0] + '年结算电量';
              }
              total = monthToYear(x[1]);
              x[1]?.forEach((y: any, i: number) => {
                month[OPTION_KEY[i + 1]] = y !== null ? parseFloat(y).toFixed(3) : y;
              });
              if (total !== null) {
                _temp.data.push({
                  title,
                  count: total,
                  ...month,
                });
              }
            });
          });
          _temp.data = descSort(_temp.data);
          return _temp;
        });
      }
      // _data = Object.entries(data).map((t: any) => {
      //   const _temp: any = {
      //     unit: stations.find((_t: any) => _t.stationId === t[0]).label,
      //     unitId: t[0],
      //     status: t[1].status,
      //     expand: false,
      //     data: [],
      //   };
      //   let year: string;
      //   Object.entries(t[1].numerical).forEach((_t: any) => {
      //     year = _t[0];
      //   });
      //   _temp.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((item) => {
      //     return {
      //       title: `${year}年${item}月`,
      //       // count: monthToYear(x[1][item - 1]),
      //       '00:00': parseFloat('0').toFixed(3),
      //       '01:00': parseFloat('0').toFixed(3),
      //       '02:00': parseFloat('0').toFixed(3),
      //       '03:00': parseFloat('0').toFixed(3),
      //       '04:00': parseFloat('0').toFixed(3),
      //       '05:00': parseFloat('0').toFixed(3),
      //       '06:00': parseFloat('0').toFixed(3),
      //       '07:00': parseFloat('0').toFixed(3),
      //       '08:00': parseFloat('0').toFixed(3),
      //       '09:00': parseFloat('0').toFixed(3),
      //       '10:00': parseFloat('0').toFixed(3),
      //       '11:00': parseFloat('0').toFixed(3),
      //       '12:00': parseFloat('0').toFixed(3),
      //       '13:00': parseFloat('0').toFixed(3),
      //       '14:00': parseFloat('0').toFixed(3),
      //       '15:00': parseFloat('0').toFixed(3),
      //       '16:00': parseFloat('0').toFixed(3),
      //       '17:00': parseFloat('0').toFixed(3),
      //       '18:00': parseFloat('0').toFixed(3),
      //       '19:00': parseFloat('0').toFixed(3),
      //       '20:00': parseFloat('0').toFixed(3),
      //       '21:00': parseFloat('0').toFixed(3),
      //       '22:00': parseFloat('0').toFixed(3),
      //       '23:00': parseFloat('0').toFixed(3),
      //     };
      //   });
      //   _temp.data = descSort(_temp.data);
      //   // Object.entries(t[1].numerical).forEach((_t: any) => {
      //   //   Object.entries(_t[1]).forEach((x: any) => {
      //   //     let total: any = '',
      //   //       title = '';
      //   //     const month: any = {};
      //   //     if (x[0].includes('plan')) {
      //   //       title = _t[0] + '年计划电量';
      //   //     }
      //   //     if (x[0].includes('operate')) {
      //   //       title = _t[0] + '年经营电量';
      //   //     }
      //   //     if (x[0].includes('guoneng')) {
      //   //       title = _t[0] + '年国能日新预测电量';
      //   //     }
      //   //     if (x[0].includes('huineng')) {
      //   //       title = _t[0] + '年金风慧能预测电量';
      //   //     }
      //   //     if (x[0].includes('settlement')) {
      //   //       title = _t[0] + '年结算电量';
      //   //     }
      //   //     total = monthToYear(x[1]);
      //   //     x[1]?.forEach((y: any, i: number) => {
      //   //       month[OPTION_KEY[i + 1]] = y !== null ? parseFloat(y).toFixed(3) : y;
      //   //     });
      //   //     if (total !== null) {
      //   //       _temp.data.push({
      //   //         title,
      //   //         count: total,
      //   //         ...month,
      //   //       });
      //   //     }
      //   //   });
      //   // });

      //   return _temp;
      // });
    }
    return _data;
  };
  //处理表头
  const getTableHeader = (data: any) => {
    let _data: any = [];
    data.forEach((t: any, i: number) => {
      let _temp: any = [];
      if (i === 0) {
        _temp = [
          {
            field: t + '_plan',
            name: '计划电量',
            parentName: t + '年计划合计',
          },
          // {
          //   field: t + '_operate',
          //   name: '经营电量',
          //   parentName: t + '年计划合计',
          // },
          {
            field: t + '_settlement',
            name: '结算电量',
            parentName: t + '年计划合计',
          },
          // {
          //   field: t + '_guoneng',
          //   name: '国能日新预测',
          //   parentName: t + '年计划合计',
          // },
          // {
          //   field: t + '_huineng',
          //   name: '金风慧能预测',
          //   parentName: t + '年计划合计',
          // },
        ];
      } else {
        _temp = [
          {
            field: t + '_plan',
            name: '计划电量',
            parentName: t + '年参考合计',
          },
          // {
          //   field: t + '_operate',
          //   name: '经营电量',
          //   parentName: t + '年参考合计',
          // },
          {
            field: t + '_settlement',
            name: '结算电量',
            parentName: t + '年参考合计',
          },
          // {
          //   field: t + '_guoneng',
          //   name: '国能日新预测',
          //   parentName: t + '年参考合计',
          // },
          // {
          //   field: t + '_huineng',
          //   name: '金风慧能预测',
          //   parentName: t + '年参考合计',
          // },
        ];
      }
      _data = _data.concat(_temp);
    });
    return _data;
  };
  //重置所有图表数据
  const clearEchars = () => {
    setEchartsPlanYearLineData({});
    setEhartDealYearBarData({});
    setEchartsPlanMonthLineData({});
  };

  const handleRadioData = (res: any) => {
    const { data, count } = getNewRadioData(res.data || {});
    if (curMarketId === 'PDBLJ') {
      //黑龙江
      setTotalRatio(Math.round((count.settlement / (count.plan == 0 ? 1 : count.plan)) * 100));
    } else {
      setTotalRatio(
        Math.round((count.settlement / (count.operate == 0 ? 1 : count.operate)) * 100),
      );
    }
    setRadioData(data);
  };

  const _onFinish = useDebounceFn(
    async (values: any) => {
      if (!isFirst) {
        setFirstLoding(true);
      }
      setLoading(true);
      clearEchars();
      setTableYearData([]);
      setTableMonthData([]);
      setTitle('全部交易单元');
      setFormData(values); //保存表单参数

      setSearchMarketId(values.marketId);
      // 查询
      const _formData: any = values,
        _date: any = moment(_formData.date).format('YYYY'),
        _referenceYear = _formData.referenceYear || [],
        _plan = _formData.plan,
        // _unit = _formData.unit;
        _unit = _formData.stationIdList;
      //参考年份参数
      const referenceYearParams = _referenceYear.map((t: any) => {
        return {
          dataTypeList: ['settlement', 'huineng', 'guoneng', 'plan', 'operate'],
          year: t,
        };
      });
      //请求表格数据
      const param: any = {
        reqDataScopes: [
          {
            dataTypeList: ['huineng', 'guoneng', 'plan', 'settlement', 'operate'],
            year: _date,
          },
          ...referenceYearParams,
        ],
        respDataTypes: ['numerical', 'proportion'],
        stationIds: _unit,
      };

      if (useNewServers.includes(values.marketId)) {
        param.marketId = values.marketId;
      }

      //发起请求
      // getBordData(_date);
      getBordData(_date, _unit);
      // getRadioData(_date);
      setCurDefaultUnit(_unit); //缓存当前的默认单元
      const res = await querypowerGenerationData(param, values.marketId).catch(() =>
        setLoading(false),
      );
      if (res?.statusCode === HttpCode.SUCCESS) {
        handleRadioData(res);
        //处理表格数据
        const data = getNewTableData(res.data || {}, _plan, values.marketId, 'PowerGenerationPlan');
        const _year = [_date, ..._referenceYear];

        //年计划
        if (_plan === '0') {
          setTableYearData(data);
          const newData = data.filter((t: any, i: number) => i !== 0);
          const header = getTableHeader(_year);
          setTableYearHead(header);
          const dataArray: any = [];
          _year.forEach((t: any) => {
            //所有交易单元为空 图表不展示对应计划
            const isAllEmpty: any = {
              plan: false,
              operate: false,
              settlement: false,
              guoneng: false,
              huineng: false,
            };
            newData.forEach((_t: any) => {
              Object.keys(planParams).forEach((x: any) => {
                !isAllEmpty[x] && _t?.[`${t}_${x}`] && (isAllEmpty[x] = true);
              });
            });
            Object.entries(planParams).forEach((x: any) => {
              isAllEmpty[x[0]] &&
                dataArray.push({
                  name: t + x[1],
                  data: newData.map((_t: any) => _t?.[`${t}_${x[0]}`] || 'NaN'),
                });
            });
          });
          clearEchars();
          setYearAllEchartsData({
            XAXIS: newData.map((t: any) => t.title),
            dataArray,
          });
          setEchartsPlanYearLineData({
            XAXIS: newData.map((t: any) => t.title),
            dataArray,
          });
        } else {
          //月计划
          setTableMonthData(data);
          let dataArray: any = [];
          //所有图例
          _year.forEach((t: any) => {
            const _temp = [
              {
                title: t + '年计划电量',
              },
              {
                title: t + '年国能日新预测电量',
              },
              {
                title: t + '经营电量',
              },
              {
                title: t + '年金风慧能预测电量',
              },
              {
                title: t + '年结算电量',
              },
            ];
            dataArray = dataArray.concat(_temp);
          });
          dataArray = dataArray.map((x: any) => {
            data.forEach((t: any) => {
              t.data.forEach((_t: any) => {
                if (_t.title === x.title) {
                  Object.values(OPTION_KEY).forEach((key: any) => {
                    x[key] = parseFloat(
                      (parseFloat(x[key] || 0) + parseFloat(_t[key] || 0)) as any,
                    ).toFixed(3);
                  });
                }
              });
            });
            return x;
          });
          //筛选有数据的图例
          dataArray = dataArray.filter((t: any) => {
            //原有长度为1 {title:xxx}
            return Object.keys(t).length > 1;
          });
          setMonthAllEchartsData({
            XAXIS: monthList,
            dataArray,
          });
          setEchartsPlanMonthLineData({
            XAXIS: monthList,
            dataArray,
          });
        }
      }
      setLoading(false);
      if (!isFirst) {
        setFirstLoding(false);
      } else {
        isFirst = false;
      }
    },
    { wait: 500 },
  );

  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      form.setFieldsValue({
        ...initialValues,
        unit: optionAll,
        marketId: province.length > 0 ? province[0].value : '',
      });
      changeMarketId(province[0]?.value);
      setCurMarketId(province[0]?.value);
      form.submit();
      //加载电量完成比例
      // getRadioData();
    },
    { wait: 500 },
  );
  //取消选中展示所有参考图
  const yearRecovery = () => {
    clearEchars();
    setTitle('全部交易单元');
    setEchartsPlanYearLineData(yearAllEchartsData);
  };
  const monthRecovery = () => {
    clearEchars();
    setTitle('全部交易单元');
    setEchartsPlanMonthLineData(monthAllEchartsData);
  };
  //年计划-选中项数据
  const selectYearItem = (record: any) => {
    let _temp: any = [];
    Object.entries(record).forEach((t: any) => {
      if (t[1] === null) return;
      if (t[0].includes('plan')) {
        _temp.push({
          name: t[0].split('_')[0] + '计划电量',
          data: t[1],
        });
      }
      if (t[0].includes('operate')) {
        _temp.push({
          name: t[0].split('_')[0] + '经营电量',
          data: t[1],
        });
      }
      if (t[0].includes('settlement')) {
        _temp.push({
          name: t[0].split('_')[0] + '结算电量',
          data: t[1],
        });
      }
      if (t[0].includes('guoneng')) {
        _temp.push({
          name: t[0].split('_')[0] + '国能日新预测',
          data: t[1],
        });
      }
      if (t[0].includes('huineng')) {
        _temp.push({
          name: t[0].split('_')[0] + '金风慧能预测',
          data: t[1],
        });
      }
    });
    clearEchars();
    _temp = _temp.sort((a: any, b: any) => {
      return b.name.substring(0, 4) === a.name.substring(0, 4)
        ? a.name.includes('计划')
          ? -1
          : 0
        : b.name.substring(0, 4) - a.name.substring(0, 4);
    });
    setEhartDealYearBarData({
      XAXIS: _temp.map((t: any) => t.name),
      dataArray: _temp.map((t: any) => t.data),
    });
    setTitle(record.title);
  };
  //月计划-选中项数据
  const selectMonthItem = (record: any) => {
    if (record.unit === echarstitle) {
      monthRecovery();
      return;
    }
    clearEchars();
    setEchartsPlanMonthLineData({
      XAXIS: monthList,
      dataArray: record.data,
    });
    setTitle(record.unit);
  };
  //控制日历可选范围
  const disabledDate = (current: any) => {
    return current && current < moment().endOf('day');
  };
  const _renderBoard = () => {
    const showPowerGenerationPlanDrawer = async (i: number) => {
      let _temp = 'null';
      switch (i) {
        case 1:
          _temp = '1';
          break;

        case 2:
          _temp = '-1';
          break;

        case 3:
          _temp = '0';
          break;

        case 4:
          _temp = '2';
          break;

        default:
          _temp = 'null';
          break;
      }
      const result = await MyDrawer.show({
        title: '发电计划总况概览',
        iconType: 1,
        MyComponent: (props: any) => (
          <PowerGenerationPlanSurvey
            treeData={stationTree}
            reSize={reSize}
            optionAll={optionAll}
            options={stations}
            status={_temp}
            year={formData.date}
            defaultItem={defaultItem}
            treeHljData={treeData}
            province={province}
            searchMarketId={searchMarketId}
            formDataValues={formData}
            {...props}
          />
        ),
      });
      if (result?.index === 1) {
      }
      getBordData(formData.date, curDefaultUnit);
      MyDrawer.dismiss();
    };
    return (
      <div className={styles.board}>
        {plannedQuantity.map((t: any, i: number) => {
          return (
            <div className={styles.item} key={i}>
              {/* <div className={styles.right}>
                                    <img src={imgString[i]} />
                                </div> */}
              <div className={styles.left}>
                <p className={styles.flex}>
                  {t.name}
                  {i !== 0 ? (
                    <Tooltip title={detailList[i - 1]}>
                      <QuestionCircleOutlined style={{ color: '#FD4F43', marginLeft: '0.04rem' }} />
                    </Tooltip>
                  ) : (
                    ''
                  )}
                </p>
                <span
                  onClick={() => {
                    showPowerGenerationPlanDrawer(i);
                  }}
                  className={styles.num}
                >
                  {t.value}
                  <span className={styles.unit}>个</span>
                </span>
              </div>
              {i !== 0 && i !== 4 ? (
                <div className={styles.radioChart}>
                  <Progress
                    type="circle"
                    percent={t.radio}
                    width={60}
                    strokeColor={colorOptions[i - 1]}
                    format={(percent) => `${percent}%`}
                  />
                </div>
              ) : (
                ''
              )}
            </div>
          );
        })}
      </div>
    );
  };
  const _renderRadio = () => {
    const showModal = async () => {
      await RadioBoxModal.show({
        value: radioData,
      });
      RadioBoxModal.dismiss();
    };
    return !expand ? (
      <div className={styles.radio}>
        <div className={styles.radioChart}>
          <Progress
            type="circle"
            percent={totalRatio}
            width={34}
            showInfo={!(totalRatio > 100)}
            format={(percent) => `${percent}`}
            strokeColor="#3CD3D3"
          />
          {totalRatio && totalRatio > 100 ? (
            <span className={styles.textNum}>{totalRatio}</span>
          ) : (
            ''
          )}
        </div>
        <div className={styles.box}>电量完成率</div>
        <div className={styles.itemBox}>
          {radioData.map((t: any, i: number) => {
            if (curMarketId === 'PDBLJ') {
              return (
                t.title +
                ' ' +
                (t.settlement && t.plan && t.plan !== 0
                  ? Math.round((t.settlement / (t.plan === '0.000' ? 1 : t.plan)) * 100) + '%'
                  : '-') +
                (i === radioData.length - 1 ? '' : '、')
              );
            } else {
              return (
                t.title +
                ' ' +
                (t.radio === '-' ? t.radio : t.radio + '%') +
                (i === radioData.length - 1 ? '' : '、')
              );
            }
          })}
        </div>
        <DownSquareOutlined
          style={{ color: 'var(--bd-primary)' }}
          onClick={() => {
            setExpand(true);
          }}
        />
      </div>
    ) : (
      <div className={styles.radio_1}>
        <div className={styles.box}>
          <div className={styles.title}>电量完成率</div>
          <div className={styles.radioChart}>
            <Progress
              type="circle"
              percent={totalRatio}
              width={88}
              showInfo={!(totalRatio > 100)}
              strokeColor="#3CD3D3"
              format={(percent) => `${percent}%`}
            />
            {totalRatio && totalRatio > 100 ? (
              <span className={styles.textNum}>{totalRatio + '%'}</span>
            ) : (
              ''
            )}
          </div>
        </div>
        <div className={styles.driver} />
        <div className={styles.group}>
          <div className={styles.title}>
            电量完成率各交易单元明细{' '}
            {radioData.length > 32 ? (
              <FullscreenOutlined
                onClick={showModal}
                style={{
                  fontSize: 12,
                  marginLeft: 12,
                  border: '2px solid var(--bd-primary)',
                  color: 'var(--bd-primary)',
                }}
              />
            ) : (
              ''
            )}
          </div>
          <div className={styles.itemBox}>
            {radioData.map((t: any, i: number) => {
              if (i < 24) {
                if (curMarketId === 'PDBLJ') {
                  return (
                    <div className={styles.item} key={i}>
                      <span>{t.title}</span>
                      <span>
                        {t.settlement && t.plan
                          ? Math.round((t.settlement / (t.plan === '0.000' ? 1 : t.plan)) * 100) +
                            '%'
                          : '-'}
                      </span>
                    </div>
                  );
                } else {
                  return (
                    <div className={styles.item} key={i}>
                      <span>{t.title}</span>
                      <span>{t.radio === '-' ? t.radio : t.radio + '%'}</span>
                    </div>
                  );
                }
              }
            })}
          </div>
        </div>
        <UpSquareOutlined
          style={{ color: 'var(--bd-primary)' }}
          onClick={() => {
            setExpand(false);
          }}
        />
      </div>
    );
  };

  const _renderContent = () => {
    const showGenerationPlan = async () => {
      const result = await MyDrawer.show({
        title: '发电计划',
        iconType: 0,
        stations: stations,
        MyComponent: (props: any) => (
          <GenerationPlan stations={stations} reSize={reSize} year={formData.date} {...props} />
        ),
      });
      if (result?.index === 1) {
        form.submit();
      }
      // getBordData(formData.date, curDefaultUnit);

      MyDrawer.dismiss();
    };
    const showMonthRatio = async (data = {}) => {
      const result = await MyDrawer.show({
        title: '月度分解比例',
        iconType: 1,
        MyComponent: (props: any) => (
          <MonthRatio stations={stations} year={formData.date} {...props} {...data} />
        ),
      });
      if (result?.index === 1) {
      }
      getBordData(formData.date, curDefaultUnit);
      MyDrawer.dismiss();
    };
    const onExpandHandler = (index: any) => {
      setTableMonthData(
        tableMonthData.map((t: any, i: number) => {
          if (index === i) {
            t.expand = !t.expand;
          }
          return t;
        }),
      );
    };

    //通过stationId去查找marketId
    const getMarketId = (unit: string) => {
      const result = stations.find((item: any) => item.stationId === unit);
      let _marketId = '';
      if (result) {
        _marketId = result.marketId;
      }
      return _marketId;
    };

    const onDateChange = async (data: any) => {
      if (!data) {
        setReferenceYearOptions([]);
        return;
      }
      const temp: any = YearOptions(moment(data).format('YYYY'));
      setReferenceYearOptions(temp);
      form.setFieldsValue({ referenceYear: [temp[0].value] });
    };
    const onUnitChange = async () => {
      if (!optionAll.length) return;
      onDateChange(moment());
    };
    const editor = async (record: any) => {
      const result = await MyDrawer.show({
        title: '发电计划',
        iconType: 0,
        stations: stations,
        MyComponent: (props: any) => (
          <GenerationPlan
            stations={stations}
            reSize={reSize}
            year={formData.date}
            selectData={record}
            {...props}
          />
        ),
      });
      if (result?.index === 1) {
        form.submit();
      }
      form.submit();
      getBordData(formData.date, curDefaultUnit);
      MyDrawer.dismiss();
    };
    const _public = async (unitId: any, type: any) => {
      const marketId = getMarketId(unitId);

      let data: any = {
        stationId: unitId,
        year: moment(formData.date).format('YYYY'),
      };
      if (useNewServers.includes(marketId)) {
        data = {
          ...data,
          marketId,
        };
      }

      const res = await publishPowerGenerationPlan(
        // {
        //   stationId: unitId,
        //   year: moment(formData.date).format('YYYY'),
        // },
        data,
        marketId,
      ).catch();
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('发布成功');
        if (type === 'month') {
          const _temp = tableMonthData.map((t: any) => {
            if (t.unitId === unitId) {
              t.status.push('1');
            }
            return t;
          });
          setTableMonthData(_temp);
        } else {
          const _temp = tableYearData.map((t: any) => {
            if (t.unitId === unitId) {
              t.status.push('1');
            }
            return t;
          });
          setTableYearData(_temp);
        }
        getBordData(formData.date, curDefaultUnit);
        await _onFinish.run(form.getFieldsValue());
      } else {
        message.error('发布失败');
      }
    };
    const toMonthRatio = (data: any) => {
      showMonthRatio({ selectData: data });
    };
    const showExport = async () => {
      const result: any = await ExportModal.show({
        stations,
        stationTree,
        optionAll,
        buttonPermissions: buttonPermissions,
        getNewTableData,

        defaultItem,
        treeData,
        province,
      });
      if (result?.index === 1) {
        message.success('计划导入成功');
        form.submit();
      }
      ExportModal.dismiss();
    };
    const showHistory = async () => {
      const result = await MyDrawer.show({
        title: '操作日志',
        iconType: 1,
        width: 800,
        MyComponent: (props: any) => (
          <HistoryShot
            stations={stations}
            treeData={stationTree}
            optionAll={optionAll}
            defaultItem={defaultItem}
            treeHljData={treeData}
            province={province}
            formData={formData}
            {...props}
          />
        ),
      });
      if (result?.index === 1) {
      }
      MyDrawer.dismiss();
    };
    const operateHanlder = (val: any) => {
      if (val.key === '1') {
        showGenerationPlan();
      } else {
        showExport();
      }
    };

    return (
      <>
        <div className={[styles.leftBox, getClassName().classNameTable].join(' ')}>
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenEcharts(!isFullScreenEcharts);
            }}
          >
            {isFullScreenEcharts ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
          <div className={styles.header}>
            <Form
              form={form}
              initialValues={initialValues}
              className={styles.formStyles}
              onFinish={_onFinish.run}
            >
              <Space size={[0, 8]} wrap>
                <Form.Item name="marketId" className={styles.marketId_item}>
                  <Select
                    options={province}
                    style={{ width: 120 }}
                    placeholder="请选择交易中心"
                    onChange={changeMarketId}
                  />
                </Form.Item>

                <Form.Item name="stationIdList" className={styles.marketId_item}>
                  <TjMarketingUnit treeData={treeData} marketId={currentProvinceInfo?.value} />
                </Form.Item>

                {/* <Form.Item name="unit" className={styles.cell_item}>
                  <TjStation width={200} options={stationTree} onChange={onUnitChange} />
                </Form.Item> */}
                <Form.Item name="plan" className={styles.cell_item}>
                  <Select options={planOption} style={{ width: 80 }} placeholder="年计划" />
                </Form.Item>
                <Form.Item
                  name="date"
                  className={styles.cell_item}
                  rules={[{ required: true, message: '请选择年份' }]}
                >
                  <DatePicker
                    className={styles.select_date}
                    // disabledDate={disabledDate}
                    onChange={onDateChange}
                    picker="year"
                  />
                </Form.Item>
                <Form.Item name="referenceYear" className={styles.cell_item}>
                  <MySelect options={referenceYearOptions} />
                </Form.Item>
                <Button className={styles.submit} type="primary" htmlType="submit">
                  查询
                </Button>
                {/* </Popconfirm> */}
                <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
                  重置
                </Button>
              </Space>
            </Form>
          </div>
          <div className={styles.tip}>
            <div className={styles.title}>{echarstitle}计划参考图</div>
          </div>
          {loading ? (
            <PageLoading />
          ) : (
            <div style={{ flex: 1 }}>
              {!echartsPlanMonthLineData?.XAXIS?.length &&
                !ehartDealYearBarData?.XAXIS?.length &&
                !echartsPlanYearLine?.XAXIS?.length && <TRDefault type="emptysm" />}
              {!!echartsPlanMonthLineData?.XAXIS?.length && (
                <ChartDealMonthLine
                  expand={expand}
                  isFullScreenEcharts={isFullScreenEcharts}
                  data={echartsPlanMonthLineData}
                  scale={reSize / 100}
                />
              )}
              {!!ehartDealYearBarData?.XAXIS?.length && (
                <ChartDealYearBar
                  expand={expand}
                  isFullScreenEcharts={isFullScreenEcharts}
                  data={ehartDealYearBarData}
                  scale={reSize / 100}
                />
              )}
              {!!echartsPlanYearLine?.XAXIS?.length && (
                <ChartDealYearLine
                  expand={expand}
                  isFullScreenEcharts={isFullScreenEcharts}
                  data={echartsPlanYearLine}
                  scale={reSize / 100}
                />
              )}
            </div>
          )}
        </div>
        <div className={[styles.rightBox, getClassName().classNameEcharts].join(' ')}>
          <div className={styles.filter_group}>
            <Dropdown
              overlay={MENU_OPTIONS(
                [
                  { type: '1', name: '手动新建' },
                  { type: '2', name: '导入新建' },
                ],
                operateHanlder,
              )}
              placement="bottomLeft"
            >
              <Button type="link" icon={<PlusCircleOutlined style={{ fontSize: 16 }} />}>
                新建发电计划
              </Button>
            </Dropdown>
            <Button
              onClick={showHistory}
              type="link"
              icon={<FileTextOutlined style={{ fontSize: 16 }} />}
            >
              操作日志
            </Button>
          </div>
          <div
            className={styles.rightArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretRightOutlined /> : <CaretLeftOutlined />}
          </div>

          {loading ? (
            <PageLoading />
          ) : (
            <div className={styles.content_box}>
              {!tableYearData.length && !tableMonthData.length && <TRDefault type="emptysm" />}
              {!!tableYearData.length && (
                <PlanYearTable
                  recovery={yearRecovery}
                  tableData={tableYearData}
                  tableHeader={tableYearHead}
                  onSelected={selectYearItem}
                  editor={(e: any) => {
                    editor(e);
                  }}
                  onPublic={_public}
                  toMonthRatio={toMonthRatio}
                />
              )}
              {!!tableMonthData.length && (
                <div className={styles.monthTable}>
                  {tableMonthData.map((t: any, i: any) => (
                    <div key={i}>
                      <div
                        className={styles.item}
                        style={{
                          borderBottom:
                            i != tableMonthData.length - 1 && !t.expand ? '1px solid #4E5154' : '',
                        }}
                      >
                        <div className={styles.left}>
                          <span
                            onClick={() => {
                              onExpandHandler(i);
                            }}
                          >
                            {!t.expand ? <CaretRightOutlined /> : <CaretDownOutlined />}
                          </span>
                          {t.unit}
                          <FileSearchOutlined
                            style={{ marginLeft: 5, color: 'var(--bd-primary)' }}
                            onClick={() => {
                              selectMonthItem(t);
                            }}
                          />
                        </div>
                        <div className={styles.right}>
                          <span
                            className={styles.custorm}
                            onClick={() => {
                              editor(t);
                            }}
                          >
                            操作
                          </span>
                          <span style={{ margin: '0 8px', color: 'var(--bd-a50)' }}>|</span>
                          <span
                            className={`${
                              t.status.includes('0') || t.status.includes('2')
                                ? styles.custorm
                                : styles.disable
                            }`}
                            onClick={() => {
                              (t.status.includes('0') || t.status.includes('2')) &&
                                _public(t.unitId, 'month');
                            }}
                          >
                            发布
                          </span>
                          <span style={{ margin: '0 8px', color: 'var(--bd-a50)' }}>|</span>
                          <span
                            className={`${styles.custorm}`}
                            onClick={() => {
                              toMonthRatio(t);
                            }}
                          >
                            月度分解比例
                          </span>
                        </div>
                      </div>
                      <PlanMonthTable
                        style={{
                          display: !t.expand ? 'none' : 'block',
                          borderRadius: 0,
                          overflowY: 'auto',
                          borderLeftWidth: 0,
                        }}
                        tableData={t.data}
                        tableHeader={tableHead_2}
                      />
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </>
    );
  };
  if (firstLoding) return <PageLoading />;
  return (
    <div className={styles.container}>
      {_renderBoard()}
      {/* {_renderRadio()}//注释电量完成率 */}
      <div className={styles.content_body}>
        <div className={styles.content}> {_renderContent()}</div>
      </div>
    </div>
  );
};

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(PowerGenerationPlan);
